import 'dart:convert';

import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:deepseek_desktop/components/ScrollControllerX.dart';
import 'package:deepseek_desktop/components/chat/ChatInput.dart';
import 'package:deepseek_desktop/components/chat/ChatSettingController.dart';
import 'package:deepseek_desktop/components/chat/ChatSettings.dart';
import 'package:deepseek_desktop/components/chat/ChatTitle.dart';
import 'package:deepseek_desktop/components/chat/message/ChatMessageWidget.dart';
import 'package:deepseek_desktop/controller/SettingController.dart';
import 'package:deepseek_desktop/entity/ChatItem.dart';
import 'package:deepseek_desktop/entity/ChatMessage.dart';
import 'package:deepseek_desktop/gpt/plugins/GPTPluginController.dart';
import 'package:deepseek_desktop/gpt/plugins/GPTPluginInterface.dart';
import 'package:deepseek_desktop/utils/Util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:file_picker/file_picker.dart';
import 'package:http/io_client.dart';

class Chat extends StatelessWidget {
  final String id;
  final RxBool isLoading = false.obs;

  Chat({super.key, required this.id});

  final ChatSettingController controller = Get.put(ChatSettingController());
  final SettingController settingController = Get.put(SettingController());
  final ScrollControllerX scrollControllerX = Get.put(ScrollControllerX());

  final GlobalKey<ScaffoldState> _scaffoldKey =
      GlobalKey<ScaffoldState>(); // 新增
  late IOClient ioClient;
  @override
  Widget build(BuildContext context) {
    Util.readFile('chats/$id.json').then((value) {
      if (value.isEmpty) {
        value = jsonEncode(
          ChatItem(
              id: id,
              name: "DeepSeek",
              avatar: "",
              lastMessage: "",
              lastMessageTime: "",
              subtitle: "思考更深，推理更强",
              selectedAttachments: []),
        );
        Util.writeFile('chats/$id.json', value);
      }
      controller.currentChat.value = ChatItem.fromJson(jsonDecode(value));
    });
    return Scaffold(
      key: _scaffoldKey,
      endDrawer: Drawer(
        width: 240,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.zero,
        ),
        child: Container(
          color: const Color.fromARGB(255, 252, 252, 252),
          child: Obx(() => controller.currentChat.value.id == '-'
              ? Container()
              : ChatSettings()),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              color: Colors.white,
              child: Column(
                children: [
                  SizedBox(
                    height: 70,
                    child: MoveWindow(
                      child: Obx(() => ChatTitle(
                          title: controller.currentChat.value.name,
                          subtitle:
                              controller.currentChat.value.subtitle.isEmpty
                                  ? '思考更深，推理更强'
                                  : controller.currentChat.value.subtitle,
                          avatar: controller.currentChat.value.avatar)),
                    ),
                  ),
                  Divider(
                    height: 1,
                    color: Colors.grey.withOpacity(0.1),
                  ),
                  Obx(() {
                    debugPrint(
                        "history: ${controller.currentChat.value.history.length}");
                    if (controller.currentChat.value.history.isEmpty) {
                      return const Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧~',
                            style: TextStyle(fontSize: 14, color: Colors.grey),
                          ),
                        ],
                      );
                    } else {
                      return const SizedBox.shrink(); // 空占位组件
                    }
                  }),
                  Expanded(
                    child: Container(
                        color: const Color.fromARGB(255, 252, 252, 252),
                        child: Obx(() => ListView.builder(
                              reverse: true,
                              controller: scrollControllerX.scrollController,
                              itemCount:
                                  controller.currentChat.value.history.length,
                              itemBuilder: (context, index) {
                                var history =
                                    controller.currentChat.value.history;
                                return buildChatMessage(
                                    history[history.length - index - 1]);
                              },
                            ))),
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.transparent,
            child: ChatInput(
              onFinish: (input, model,
                  {showChat = true,
                  required showStopButton,
                  required isSending,
                  required isGrayColor,
                  required isBeforeRenderCancel,
                  required isAfterRenderCancel}) {
                debugPrint("isSending: $isSending");

                if (input.isEmpty) {
                  return;
                }

                controller.currentChat.value.history.add(ChatMessage(
                    content: input,
                    role: 'user',
                    time: '',
                    showChat: showChat));
                // 只保留最后50条消息
                if (controller.currentChat.value.history.length > 50) {
                  controller.currentChat.value.history =
                      controller.currentChat.value.history.sublist(
                          controller.currentChat.value.history.length - 50);
                }
                Util.writeFile('chats/${controller.currentChat.value.id}.json',
                    jsonEncode(controller.currentChat.value));
                controller.currentChat.refresh();

                // build request message
                int dialogCount = controller.currentChat.value.dialogCount;
                int allLength = controller.currentChat.value.history.length;
                List<ChatMessage> reqMsg = [];
                if (allLength > dialogCount) {
                  reqMsg = controller.currentChat.value.history
                      .sublist(allLength - dialogCount);
                } else {
                  for (ChatMessage msg
                      in controller.currentChat.value.history) {
                    reqMsg.add(msg);
                  }
                }
                if (controller.currentChat.value.system.isNotEmpty) {
                  // 在最前面加上系统消息
                  reqMsg.insert(
                      0,
                      ChatMessage(
                          content: controller.currentChat.value.system,
                          role: 'system',
                          time: '',
                          showChat: showChat));
                }

                // 请求GPT
                ChatMessage replyChatMessage = ChatMessage(
                    content: '',
                    role: 'assistant',
                    time: '',
                    showChat: showChat);
                // 添加助手回复到历史记录
                controller.currentChat.update((val) {
                  controller.currentChat.value.history.add(replyChatMessage);
                });

                isLoading.value = true;
                isSending.value = true;
                showStopButton.value = false;
                isGrayColor.value = false;
                isBeforeRenderCancel.value = false;
                // 监听 isBeforeRenderCancel 的值变化
                var cancelSubscription;
                cancelSubscription = isBeforeRenderCancel.listen((isCancel) {
                  debugPrint("isCancel: $isCancel");
                  if (isCancel && !isAfterRenderCancel.value) {
                    // 关闭HTTP连接
                    ioClient.close();

                    // 更新状态
                    isLoading.value = false;
                    isSending.value = false;
                    showStopButton.value = false;
                    isGrayColor.value = true;
                    // 先取消监听，避免重复触发
                    cancelSubscription?.cancel();

                    // 删除对应的助手回复
                    controller.currentChat.update((val) {
                      val?.history.remove(replyChatMessage);
                    });

                    // 延迟一小段时间再保存聊天记录，确保所有状态都已更新
                    Future.delayed(const Duration(milliseconds: 100), () {
                      try {
                        Util.writeFile(
                            'chats/${controller.currentChat.value.id}.json',
                            jsonEncode(controller.currentChat.value));
                      } catch (e) {
                        debugPrint('保存聊天记录失败: $e');
                      }
                    });
                  }
                });
                // 加载插件
                List<GPTPluginInterface> plugins = [];
                for (GPTPluginInterface plugin in GPTPluginController.plugins) {
                  if (controller.currentChat.value.plugins
                      .contains(plugin.name)) {
                    plugins.add(plugin);
                  }
                }
                // 保存客户端引用，以便在取消时可以关闭连接
                ioClient = Util.askGPT(
                    settingController.setting.value.apiSetting.isCustom
                        ? settingController.setting.value.apiSetting.baseUrl
                        : 'https://api.deepseek.com/',
                    model,
                    controller.currentChat.value.temperature,
                    settingController.setting.value.apiSetting.accessToken,
                    plugins,
                    reqMsg, (result, finish) {
                  showStopButton.value = true;
                  isAfterRenderCancel.value = true;
                  // 更新助手回复内容
                  controller.currentChat.update((val) {
                    replyChatMessage.content = result;
                  });

                  if (finish) {
                    isLoading.value = false;
                    showStopButton.value = false;
                    isSending.value = false;
                    isGrayColor.value = true;

                    // 取消监听
                    cancelSubscription.cancel();
                    // 保存聊天记录
                    Util.writeFile(
                        'chats/${controller.currentChat.value.id}.json',
                        jsonEncode(controller.currentChat.value));
                  }
                }, (err) {
                  // 取消监听
                  cancelSubscription.cancel();

                  isLoading.value = false;

                  // 保存更新后的聊天记录
                  Util.writeFile(
                      'chats/${controller.currentChat.value.id}.json',
                      jsonEncode(controller.currentChat.value));
                  controller.currentChat.refresh();

                  debugPrint(err);
                }, isSending: isSending, isGrayColor: isGrayColor);
              },
            ),
          )
        ],
      ), // 右侧空占位，抽屉覆盖
    );
  }

  Widget buildChatMessage(ChatMessage message) {
    if (message.showChat == true) {
      return ChatMessageWidget(
        content: message.content,
        nicker: message.role == 'user'
            ? settingController.setting.value.profileSetting.nicker
            : controller.currentChat.value.name,
        isMe: message.role == 'user',
        avatar: message.role == 'user'
            ? settingController.setting.value.profileSetting.avatar
            : controller.currentChat.value.avatar,
        time: '',
        isLoading: message.role == 'assistant' &&
            isLoading.value &&
            message.content.isEmpty,
        onAvatarTap: message.role == 'assistant'
            ? () {
                _scaffoldKey.currentState?.openEndDrawer();
              }
            : null,
      );
    } else {
      return const SizedBox.shrink();
    }
  }
}
